package com.djmw.mouse.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import com.djmw.mouse.entity.Cv;
import com.djmw.mouse.repository.CvDao;
import com.djmw.mouse.repository.PositionHistoryDao;

//Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional(readOnly = true)
public class CvService {

    @Autowired
    private CvDao cvDao;
    @Autowired
    private PositionHistoryDao positionHistoryDao;

    public Cv getCv(Long id) {
        return cvDao.findOne(id);
    }

    @Transactional(readOnly = false)
    public void saveCv(Cv entity) {
        cvDao.save(entity);
    }

    @Transactional(readOnly = false)
    public void deleteCv(Long id) {
        cvDao.changeStatus(id, Cv.STATUS_DELETED);
    }

    public Page<Cv> getMemberCv(Long memberId, boolean includeDeletedCv) {
        PageRequest pageRequest = new PageRequest(0, 100, new Sort(Direction.ASC, "name"));
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        filters.put("memberUser.id", new SearchFilter("memberUser.id", Operator.EQ, memberId));
        if (!includeDeletedCv) {
            filters.put("status", new SearchFilter("status", Operator.LT, Cv.STATUS_DELETED));
        }
        Specification<Cv> spec = DynamicSpecifications.bySearchFilter(filters.values(), Cv.class);
        return cvDao.findAll(spec, pageRequest);
    }

    public List<Cv> getMemberCvList(Long memberId) {
        return cvDao.findByMemberUserId(memberId);
    }
}
